package org.jash.comment

import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
open class BaseActivity<B: ViewDataBinding, VM: ViewModel> : AppCompatActivity() {
    private val target by lazy {
        (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments
    }
    protected val binding: B by lazy {
        (target[0] as Class<B>).getDeclaredMethod("inflate", LayoutInflater::class.java)
            .apply { isAccessible = true }
            .invoke(null, LayoutInflater.from(this)) as B
    }
    protected val vm:VM by lazy {
        ViewModelProvider.create(this)[target[1] as Class<VM>]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
}